# -*- coding: utf-8 -*-

import time
import os
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
import parse_log_util

switch_list = [
    'HDMI Jack',
    'Headphone Jack',
    'Headset Mic Jack',
    'LineIn Jack',
    'Rear HeadPhone Jack',
    'Rear Mic Jack',
    'LineIn Capture Switch',
    'AUDIO_INTF2_SWITCH Switch',
    'AUDIO_INTF3_SWITCH Switch',
    'Headset Mic Capture Switch',
    'Headset Playback Switch',
    'INVERT_HEADSET_SWITCH',
    'Rear Headphone Playback Switch',
    'Rear Mic Capture Switch',
    'Speaker Playback Switch'
]

map = {
    "amixer -c0 cget iface=CARD,name='HDMI Jack'": ": values=on",
    "amixer -c0 cget iface=CARD,name='Headphone Jack'": ": values=off",
    "amixer -c0 cget iface=CARD,name='Headset Mic Jack'": ": values=on",
    "amixer -c0 cget iface=CARD,name='LineIn Jack'": ": values=off",
    "amixer -c0 cget iface=CARD,name='Rear HeadPhone Jack'": ": values=on",
    "amixer -c0 cget iface=CARD,name='Rear Mic Jack'": ": values=off",
    "amixer -c0 cget iface=MIXER,name='LineIn Capture Switch'": ": values=on",
    "amixer -c0 cget iface=MIXER,name='AUDIO_INTF2_SWITCH Switch'": ": values=off",
    "amixer -c0 cget iface=MIXER,name='AUDIO_INTF3_SWITCH Switch'": ": values=on",
    "amixer -c0 cget iface=MIXER,name='Headset Mic Capture Switch'": ": values=off",
    "amixer -c0 cget iface=MIXER,name='Headset Playback Switch'": ": values=on",
    "amixer -c0 cget iface=MIXER,name='INVERT_HEADSET_SWITCH'": ": values=off",
    "amixer -c0 cget iface=MIXER,name='Rear Headphone Playback Switch'": ": values=on",
    "amixer -c0 cget iface=MIXER,name='Rear Mic Capture Switch'": ": values=off",
    "amixer -c0 cget iface=MIXER,name='Speaker Playback Switch'": ": values=on",
}

amixer_switch_list = []

def get_switch(cmd):
    # val = "".join(os.popen(cmd).readlines())
    val = map.get(cmd)
    amixer_switch_list.append(cmd)
    amixer_switch_list.append(val)
    return val

def get_switch_val(switch):
    if switch.endswith('Jack'):
        cmd = "amixer -c0 cget iface=CARD,name='{}'".format(switch)
    elif switch.upper().endswith('SWITCH'):
        cmd = "amixer -c0 cget iface=MIXER,name='{}'".format(switch)
    
    print(cmd)

    val = get_switch(cmd)
    val = val.replace(" ", "").replace(":values=", "").replace("\n", "")
    if val == "on":
        val = 1
    elif val == "off":
        val = 0
    else:
        val = -1
    return val

root = tk.Tk()  # 创建一个根窗口
root.title("Switch/Port")
root.geometry("800x1200")

notebook = ttk.Notebook(root)  # 创建一个Notebook小部件

# 创建 Style 对象
style = ttk.Style()

# 设置 Tab 页面的内边距
style.configure("TNotebook.Tab", padding=(10, 5))

# 创建并添加第二个标签页（Frame）
tab1 = tk.Frame(notebook)
# 创建并添加第一个标签页（Frame）
tab2 = tk.Frame(notebook)
# 创建并添加第二个标签页（Frame）
tab3 = tk.Frame(notebook)

# **************************************************************************************************
# tab1
def clear_log():
    print("clear log")
    result_label_tab1.config(text="clear log")
    
    if os.path.exists('/var/log/'):
        for file_name in os.listdir('/var/log/'):
            if 'kern' in file_name:
                full_file_name = '/var/log/' + file_name
                os.remove(full_file_name)

            if 'syslog' in file_name:
                full_file_name = '/var/log/' + file_name
                os.remove(full_file_name)
    else:
        print('/var/log/ not exists')

    if os.path.exists('/tmp/'):
        for file_name in os.listdir('/tmp/'):
            if 'hwaudioservice' in file_name:
                full_file_name = '/tmp/' + file_name
                os.remove(full_file_name)
    else:
        print('/tmp/ not exists')

    print("clear log success")
    result_label_tab1.config(text="clear log success")

def select_file(): 
    print("开始清洗日志")
    result_label_tab1.config(text="开始清洗日志")
    # 打开文件选择对话框 
    file_path = filedialog.askopenfilename(  
        title="选择文件",  # 对话框标题 
        filetypes=[("文本文件", "*.log"), ("文本文件", "*.txt"), ("所有文件", "*.*")]  # 文件类型过滤 
    ) 
    
    if file_path:  # 如果用户选择了文件
        print(f"日志路径：{file_path}") 
        # 在标签中显示文件路径 
        parse_log_util.parse_log(file_path)
    print("清洗日志完成：{}".format(file_path))
    result_label_tab1.config(text="清洗日志完成：{}".format(file_path))

# 创建按钮
clear_btn = tk.Button(
    tab1,
    text="清除历史日志",
    command=clear_log,
    bg="#4CAF50",
    fg="white",
    padx=20
)
clear_btn.grid(row=1, column=0, padx=(15, 0), pady=15)

# 创建按钮
select_btn = tk.Button(
    tab1,
    text="清洗kern日志",
    command=select_file,
    bg="#4CAF50",
    fg="white",
    padx=20
)
select_btn.grid(row=2, column=0, padx=(15, 0), pady=15)

# 显示结果的标签
result_label_tab1 = tk.Label(tab1, text="", fg="blue")
result_label_tab1.grid(row=12, column=1, padx=(0, 10), pady=10)

# **************************************************************************************************
# tab2
label_list = []
radio_list = []
intVar_list = []
# val_list = []
radio_text_val_list = [('on', 1), ('off', 0)]

for i in range(len(switch_list)):
    switch = switch_list[i]
    label = tk.Label(tab2, text=switch)
    label.grid(row=i+1, column=0, padx=(10, 0), pady=10)
    label_list.append(label)
    
    intVar = tk.IntVar()
    list = []
    col_index = 0
    for t, v in radio_text_val_list:
        radio = tk.Radiobutton(tab2, text=t, variable=intVar, value=v, state='disabled')
        radio.grid(row=i+1, column=col_index + 1, padx=(10, 0), pady=10)
        list.append(radio)
        col_index = col_index + 1

    radio_list.append(list)
    intVar_list.append(intVar)

# 显示结果的标签
result_label_tab2 = tk.Label(tab2, text="", fg="blue")
result_label_tab2.grid(row=16, column=1, padx=(0, 10), pady=10)

# 按钮功能
def refresh_switch():
    print("开始刷新Switch数据")
    result_label_tab2.config(text="开始刷新Switch数据", state=tk.DISABLED)

    for i in range(len(switch_list)):
        intVar = intVar_list[i]
        switch = switch_list[i]
        val = get_switch_val(switch)
        if val != -1:
            intVar.set(val)
    
    print("刷新Switch数据完成")
    result_label_tab2.config(text="刷新Switch数据", state=tk.NORMAL)
 
def download_btn():
    print("开始导出Switch数据")
    result_label_tab2.config(text="downloading", state=tk.NORMAL)
    file_name = os.getcwd() + os.sep + 'port_switch_{}.txt'.format(int(time.time()))
    with open(file_name, 'w') as file:
        for line in amixer_switch_list:
            file.write(line + '\n')
    print("导出Switch数据完成：{}".format(file_name))
    result_label_tab2.config(text="导出Switch数据完成：{}".format(file_name), state=tk.NORMAL)

# 创建按钮
refresh_btn = tk.Button(
    tab2,
    text="刷新Switch数据",
    command=refresh_switch,
    bg="#4CAF50",
    fg="white",
    padx=20
)
refresh_btn.grid(row=17, column=0, padx=(15, 0), pady=15)

download_btn = tk.Button(
    tab2,
    text="导出Switch数据",
    command=download_btn,
    bg="#4CAF50",
    fg="white",
    padx=20
)
download_btn.grid(row=17, column=1, padx=(15, 0), pady=15)

tk.Label(tab3, text='This is Tab3 content!').pack()  # 只包含一个标签

# 将两个页面添加到Notebook中，并赋予对应的标题
notebook.add(tab1, text='常用工具  ')
notebook.add(tab2, text='导出switch  ')
notebook.add(tab3, text='Tab 3  ')

def on_tab_changed(event):
    # 获取当前选中的标签页索引 
    current_tab_index = notebook.index(notebook.select()) 
    print(f"切换到标签页 {current_tab_index}")

    if current_tab_index == 1:
        refresh_switch()
 
# 绑定事件
notebook.bind("<<NotebookTabChanged>>",  on_tab_changed)

# 将Notebook添加到根窗口中
notebook.pack(expand=True, fill='both')

root.mainloop()